package com.box1312.fishpond;

import java.io.Closeable;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.iq80.leveldb.DBIterator;

public class LevelIterator implements Iterator<Map.Entry<String, String>>, Closeable {

  private final DBIterator iterator;
  private final String end;

  public LevelIterator(LevelDB db, String start, String end) {
    this.iterator = db.iterator();
    iterator.seek(LevelDB.bytes(start));
    this.end = end;
  }

  @Override
  public boolean hasNext() {
    boolean hasNext = iterator.hasNext();
    boolean islessOrEqualEnd = false;
    if (hasNext) {
      String key = LevelDB.asString(iterator.peekNext().getKey());
      islessOrEqualEnd = key.compareTo(end) <= 0;
    }
    return hasNext && islessOrEqualEnd;
  }

  @Override
  public Map.Entry<String, String> next() {
    Map.Entry<String, String> ret = null;
    Entry<byte[], byte[]> entry = iterator.next();
    String key = LevelDB.asString(entry.getKey());
    String value = LevelDB.asString(entry.getValue());
    ret = new AbstractMap.SimpleImmutableEntry<String, String>(key, value);
    return ret;
  }

  @Override
  public void remove() {
    iterator.remove();
  }

  @Override
  public void close() throws IOException {
    iterator.close();
  }

}
